﻿using FlyingHat.Common.Helper;
using FreeRedis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace FlyingHat.Extensions.Redis
{
    public class RedisHelper : IRedisHelper
    {
        private readonly ILogger<RedisHelper> logger;
        private readonly IConfiguration configuration;
        private static Lazy<RedisClient>? redisClient;
        public RedisHelper(ILogger<RedisHelper> logger, IConfiguration configuration)
        {
            this.logger = logger;
            this.configuration = configuration;

            redisClient = new(() =>
            {
                var redisString = configuration.GetConnectionString("RedisConnectString");
                var r = new RedisClient(redisString)
                {
                    Serialize = obj => SerializeHelper.SerializeType(obj),
                    Deserialize = (json, type) => SerializeHelper.DeserializeType(json, type)
                };
                r.Notice += (s, e) => Console.WriteLine(e.Log);
                return r;
            });
        }


        RedisClient Cilent
        {
            get
            {
                if (redisClient == null)
                {
                    redisClient = new(() =>
                     {
                         var redisString = configuration.GetConnectionString("RedisConnectString");
                         var r = new RedisClient(redisString)
                         {
                             Serialize = obj => SerializeHelper.SerializeType(obj),
                             Deserialize = (json, type) => SerializeHelper.DeserializeType(json, type)
                         };
                         r.Notice += (s, e) => Console.WriteLine(e.Log);
                         return r;
                     });
                }
                return redisClient.Value;
            }
        }

        public bool Set<T>(string key, T value)
        {
            Cilent.Set(key, value);
            return true;
        }
        public bool Set<T>(string key, T value, int timeoutSeconds)
        {
            if (timeoutSeconds <= 0)
            {
                return false;
            }
            Cilent.Set(key, value, timeoutSeconds);
            return true;
        }
        public T Get<T>(string key)
        {
            return Cilent.Get<T>(key);
        }


        public bool Exists(string key)
        {
            return Cilent.Exists(key);
        }
    }
}
